package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Contact;
import com.kaishengit.entity.ContactNote;
import com.kaishengit.entity.User;
import com.kaishengit.entity.UserProject;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class ContactNoteDao {
	private DBHelp<ContactNote> db=new DBHelp<ContactNote>();

	public List<ContactNote> findById(String contactId){
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT tn.id,content,tn.createtime,t_contact_id,t_user_id,tu.`name` AS username,`password`,tc.`name`,company,cellphone,phone,email,address,website,introduction,t_project_id,tc.createtime AS ctime ,weibo FROM t_contactnote AS tn ");
		sql.append("LEFT JOIN t_contact AS tc ON tc.id=tn.t_contact_id ");
		sql.append("LEFT JOIN t_user AS tu ON tu.id=tn.t_user_id ");
		sql.append("WHERE tn.t_contact_id=? ");
		return db.executeQueryForList(sql.toString(), new ContactNoteRowMapper(), contactId);
	}
	public void save(ContactNote cn) {
		final String sql="INSERT INTO t_contactnote(id,content,createtime,t_contact_id,t_user_id)VALUES(?,?,?,?,?)";
		db.executeSQL(sql,cn.getId(),cn.getContent(),cn.getCreatetime(),cn.getContactId(),cn.getUserId());
	}
	
	 private class ContactNoteRowMapper implements RowMapper<ContactNote>{

		public ContactNote mapperRow(ResultSet rs) throws SQLException {
			ContactNote cn=new ContactNote();
			cn.setId(rs.getString("id"));
			cn.setContent(rs.getString("content"));
			cn.setCreatetime(rs.getString("createtime"));
			cn.setContactId(rs.getString("t_contact_id"));
			cn.setUserId(rs.getString("t_user_id"));
			
			Contact c=new Contact();
			c.setId(rs.getString("t_contact_id"));
			c.setName(rs.getString("name"));
			c.setAddress(rs.getString("address"));
			c.setCellphone(rs.getString("cellphone"));
			c.setPhone(rs.getString("phone"));
			c.setCreatetime(rs.getString("ctime"));
			c.setCompany(rs.getString("company"));
			c.setEmail(rs.getString("email"));
			c.setIntroduction(rs.getString("introduction"));
			c.setWebsite(rs.getString("website"));
			c.setWeibo(rs.getString("weibo"));
			c.setProjectId(rs.getString("t_project_id"));
			
			cn.setContact(c);
			cn.setContactId(rs.getString("t_contact_id"));
			
			User user=new User();
			user.setId(rs.getString("t_user_id"));
			user.setName(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			
			cn.setUser(user);
			cn.setUserId(rs.getString("t_user_id"));
			return cn;
		}
	 }

	public void del(String id) {
		final String sql="delete from t_contactnote where t_contact_id=?";
		db.executeSQL(sql, id);
	}


	
	 
}
